<?php

namespace app\common\library;

use think\Hook;

/**
 * 订阅消息推送
 */
class Send 
{
   protected $appid;
    protected $appSecret;
    public function __construct(Request $request = null)
    {
        
        $this->appid ='wx5dd295e6ff41914c';
        $this->appSecret ='9974726f6c355f80c76d24eeb7f1862c';

    }
   // 发送 POST 请求的函数
    function send_post($url, $post_data){
        $options = array(
            'http' => array(
                'method'  => 'POST',
                'header'  => 'Content-type:application/json',
                'content' => $post_data,
                'timeout' => 60
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }

    // 小程序 appID 和 appSecret 获取 token
    public function getAccessToken($appid,$appsecret){
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret;
        $html = file_get_contents($url);
        $output = json_decode($html, true);
        $access_token = $output['access_token'];
        return $access_token;
    }

    public function send($open_id,$template_id,$data,$page){

        $post_data = array(
            // 用户的 openID，可用过 wx.getUserInfo 获取
            "touser"           => $open_id,
            // 小程序后台申添加的订阅消息模板 ID
            "template_id"      => $template_id,
            // 点击模板消息后跳转到的页面，可以传递参数
             "page"             => $page,
            // 发送给用户的数据

            "data"             => $data
        );
        file_put_contents('dingyue2.txt',date('Y-m-d H:i:s').json_encode($post_data, true).PHP_EOL, FILE_APPEND);
        $appid=$this->appid;
        $appsecret=$this->appSecret;
        //     // 这里替换为你的 appID 和 appSecret
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=".$this->getAccessToken($appid,$appsecret);

        $data = json_encode($post_data, true);

        $return = $this->send_post($url, $data);

        file_put_contents('dingyue.txt',date('Y-m-d H:i:s').json_encode($return, true).PHP_EOL, FILE_APPEND);
    }
     
}
